import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import router from "@/router/index";
import userApi from "@/api/user";
import { staticRoutes, runRouter, anyRouter } from "@/router/routes"; //引入静,动,任意路由
import cloneDeep from "lodash/cloneDeep";
// dynamic动态
function showDynamicRouter(runRouter, userInfo) {
  // 过滤用户的返回路由是否匹配动态路由
  return runRouter.filter((item) => {
    if (userInfo.routes.includes(item.name)) {
      if (item.children && item.children.length > 1) {
        //如还有子路由
        item.children = showDynamicRouter(item.children, userInfo);
      }
      return true;
    }
  });
}

//初始化数据
const getDefaultState = () => {
  return {
    token: "",
    name: "",
    avatar: "",
    userInfo: {
      routes: [],
      buttons: [],
      roles: [],
      name: "",
      avatar: "",
    },
  };
};

// 初始数据
const state = () => {
  return {
    token: getToken() || "",
    name: "",
    avatar: "",
    userInfo: {},
  };
};

const mutations = {
  // 重置清空
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    try {
      let res = await userApi.login(userInfo);
      commit("SET_TOKEN", res.token);
      // localStorage.setItem("user_token",res.token)
      setToken(res.token); //调用auth中自己定义的settoken
    } catch (error) {
      return Promise.reject(new Error("请求登录失败"));
    }
  },

  // 获取用户信息
  async getInfo({ commit }) {
    try {
      let res = await userApi.getInfo();
      commit("SET_NAME", res.name);
      commit("SET_AVATAR", res.avatar);
      commit("SET_USERINFO", res);
      // 获取用户信息之后,进行过滤动态路由信息
      let filterRunRouter = showDynamicRouter(runRouter, res);
      // 过滤后的信息,需要添加到路由中router.onready是为了让动态加载的路由加载完

      // router.onReady(()=>{
      // 可以修改layout中"src\layout\components\Sidebar\index.vue"中计算属性的routes来自行做菜单侧边栏展示渲染
      router.options.routes = staticRoutes.concat(
        (filterRunRouter),
        anyRouter
      );
      router.addRoutes(filterRunRouter.concat(anyRouter));
      // })
      return "OK";
    } catch (error) {
      return Promise.reject(new Error("请求获取用户信息失败"));
    }
  },

  //清空数据
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
  // 退出登录
  async logout({ commit, dispatch }) {
    await userApi.logout();
    resetRouter(); //重置路由
    dispatch("resetToken");
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
